package com.sky.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.shortlink.admin.common.biz.user.UserContext;
import com.sky.shortlink.admin.convention.exception.ClientException;
import com.sky.shortlink.admin.convention.result.Result;
import com.sky.shortlink.admin.dao.entity.GroupDO;
import com.sky.shortlink.admin.dao.mapper.GroupMapper;
import com.sky.shortlink.admin.dto.req.ShortLinkGroupSaveReqDTO;
import com.sky.shortlink.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.sky.shortlink.admin.dto.resp.ShortLinkGroupUpdateDTO;
import com.sky.shortlink.admin.remote.dto.ShortLinkActualRemoteService;
import com.sky.shortlink.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.sky.shortlink.admin.remote.dto.resp.ShortLinkGroupRespDTO;
import com.sky.shortlink.admin.service.GroupService;
import com.sky.shortlink.admin.toolkit.RandomGenerator;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.sky.shortlink.admin.common.constant.RedisCacheConstant.LOCK_GROUP_CREATE_KEY;

/**
 * @author Blue sky
 * @Description 分组接口实现层
 * @create 2024-02-18 10:18
 */
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {
    private final ShortLinkActualRemoteService shortLinkActualRemoteService;

    /**
     * 后续重构为 SpringCloud Feign 调用
     */
    private final RedissonClient redissonClient;

    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;

    @Override
    public void saveGroup(ShortLinkGroupSaveReqDTO saveReqDTO, String username) {
        RLock lock = redissonClient.getLock(String.format(LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try {
        //生成一个不重复的6位随机id
        String gid;
        while(true){
            gid = RandomGenerator.generateRandom();
            if(!hasGid(saveReqDTO,gid,username)){ //如果gid之前不存在
                break;
            }
        }
        //插入数据
        GroupDO groupDO = GroupDO.builder()
                .name(saveReqDTO.getName())
                .gid(gid)
                .sortOrder(0)
                .username(username)
                .build();
            //使用分布式锁 限定group分组创建
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, username)
                    .eq(GroupDO::getDelFlag, 0);
            List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
            if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() >= groupMaxNum) {
                throw new ClientException(String.format("已超出最大分组数：%d", groupMaxNum));
            }
            baseMapper.insert(groupDO);
    } finally {
            lock.unlock();
        }
    }

    @Override
    public void saveGroup(ShortLinkGroupSaveReqDTO saveReqDTO) {
        saveGroup(saveReqDTO, UserContext.getUsername());

    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime);
        List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);

        //下面这段代码是老师写的很不优雅
        Result<List<ShortLinkGroupCountQueryRespDTO>> listResult = shortLinkActualRemoteService
                .listGroupShortLinkCount(groupDOList.stream().map(GroupDO::getGid).toList());
        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(groupDOList, ShortLinkGroupRespDTO.class);
        shortLinkGroupRespDTOList.forEach(each -> {
            Optional<ShortLinkGroupCountQueryRespDTO> first = listResult.getData().stream()
                    .filter(item -> Objects.equals(item.getGid(), each.getGid()))
                    .findFirst();
            first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return shortLinkGroupRespDTOList;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateDTO updateDTO) {
        LambdaUpdateWrapper<GroupDO> wrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, updateDTO.getGid())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setName(updateDTO.getName());
        baseMapper.update(groupDO, wrapper);
    }

    @Override
    public void deleteGroup(String gid) {
        //软删除
        LambdaUpdateWrapper<GroupDO> wrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        baseMapper.update(groupDO, wrapper);
    }

    @Override
    public void SortGroup(List<ShortLinkGroupSortReqDTO> list) {
        list.forEach(item -> {

            LambdaUpdateWrapper<GroupDO> wrapper = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, item.getGid())
                    .eq(GroupDO::getDelFlag, 0);
            GroupDO groupDO = new GroupDO();
            groupDO.setSortOrder(item.getSortOrder());
            baseMapper.update(groupDO, wrapper);
        });

    }

    private Boolean hasGid(ShortLinkGroupSaveReqDTO saveReqDTO,String gid, String username) {
        LambdaQueryWrapper<GroupDO> wrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, Optional.ofNullable(UserContext.getUsername()).orElse(username))
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getName, saveReqDTO.getName())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = baseMapper.selectOne(wrapper);
        return groupDO != null;
    }
}
